package com.ccx.demo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


public class RemoteShellExecutor {

    private Connection conn;
    private String ip;
    private String username;
    private String password;
    private static final int TIME_OUT = 0;// 表示不超时

    public RemoteShellExecutor() {
    }

    public RemoteShellExecutor(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }
/**
 * 构造函数
 *
 * @param ip       远程ip
 * @param username 远程机器用户名
 * @param password 远程机器密码
 */


    /**
     * 登录
     *
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(username, password);
    }

    /**
     * 执行脚本
     *
     * @param shell
     * @return
     * @throws Exception
     */
    public ArrayList<String> exec(String shell) throws Exception {
        int ret = -1;
        ArrayList<String> strings = new ArrayList<>();
        try {
            if (login()) {
                Session session = conn.openSession();
                session.execCommand(shell);
                InputStream stdout = new StreamGobbler(session.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                String s = "";
                while ((s = br.readLine()) != null) {
                    strings.add(s);
                }

            } else {
                throw new Exception("登录远程机器失败" + ip); //
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(conn!=null){
                conn.close();
            }
        }
        return strings;
    }
}